/**
 * GitLab项目导入对话框
 * @author zhou.xu
 * @date 2024-03-12 21:30:00
 */
package com.mayfool.gitmanager.ui.dialog;

import com.mayfool.gitmanager.core.entity.GitLabProject;
import com.mayfool.gitmanager.core.service.GitLabService;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.io.File;
import java.io.Serial;
import java.util.List;

public class GitLabImportDialog extends JDialog {
    @Serial
    private static final long serialVersionUID = 1L;
    
    private final JTextField gitlabUrlField;
    private final JTextField usernameField;
    private final JPasswordField passwordField;
    private final JTextField localPathField;
    private final JButton browseButton;
    private final JButton importButton;
    private final JButton cancelButton;
    private final JTable projectTable;
    private final DefaultTableModel tableModel;
    private final JCheckBox downloadCheckBox;
    

    public GitLabImportDialog(Frame owner) {
        super(owner, "导入GitLab项目", true);

        // 初始化组件
        gitlabUrlField = new JTextField(30);
        usernameField = new JTextField(20);
        passwordField = new JPasswordField(20);
        localPathField = new JTextField(30);
        browseButton = new JButton("浏览");
        importButton = new JButton("导入");
        cancelButton = new JButton("取消");
        downloadCheckBox = new JCheckBox("下载到本地");
        
        // 初始化表格
        String[] columnNames = {"选择", "项目名称", "项目路径", "可见性"};
        tableModel = new DefaultTableModel(columnNames, 0) {
            @Override
            public Class<?> getColumnClass(int column) {
                return column == 0 ? Boolean.class : String.class;
            }
        };
        projectTable = new JTable(tableModel);
        
        initComponents();
        setupLayout();
        setupListeners();
    }
    
    private void initComponents() {
        // 设置表格列宽
        projectTable.getColumnModel().getColumn(0).setPreferredWidth(50);
        projectTable.getColumnModel().getColumn(1).setPreferredWidth(200);
        projectTable.getColumnModel().getColumn(2).setPreferredWidth(300);
        projectTable.getColumnModel().getColumn(3).setPreferredWidth(100);
        
        // 添加表格选择列
        projectTable.getTableHeader().setReorderingAllowed(false);
        projectTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    }
    
    private void setupLayout() {
        setLayout(new BorderLayout(10, 10));
        
        // 创建表单面板
        JPanel formPanel = new JPanel(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(5, 5, 5, 5);
        
        // GitLab URL
        gbc.gridx = 0; gbc.gridy = 0;
        formPanel.add(new JLabel("GitLab地址:"), gbc);
        gbc.gridx = 1; gbc.fill = GridBagConstraints.HORIZONTAL;
        formPanel.add(gitlabUrlField, gbc);
        
        // 用户名
        gbc.gridx = 0; gbc.gridy = 1;
        formPanel.add(new JLabel("用户名:"), gbc);
        gbc.gridx = 1;
        formPanel.add(usernameField, gbc);
        
        // 密码
        gbc.gridx = 0; gbc.gridy = 2;
        formPanel.add(new JLabel("密码:"), gbc);
        gbc.gridx = 1;
        formPanel.add(passwordField, gbc);
        
        // 本地路径
        gbc.gridx = 0; gbc.gridy = 3;
        formPanel.add(new JLabel("本地路径:"), gbc);
        gbc.gridx = 1;
        JPanel pathPanel = new JPanel(new BorderLayout());
        pathPanel.add(localPathField, BorderLayout.CENTER);
        pathPanel.add(browseButton, BorderLayout.EAST);
        formPanel.add(pathPanel, gbc);
        
        // 下载选项
        gbc.gridx = 1; gbc.gridy = 4;
        formPanel.add(downloadCheckBox, gbc);
        
        // 按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
        buttonPanel.add(importButton);
        buttonPanel.add(cancelButton);
        
        // 主面板布局
        add(formPanel, BorderLayout.NORTH);
        add(new JScrollPane(projectTable), BorderLayout.CENTER);
        add(buttonPanel, BorderLayout.SOUTH);
        
        // 设置对话框大小和位置
        pack();
        setLocationRelativeTo(getOwner());
    }
    
    private void setupListeners() {
        // 浏览按钮
        browseButton.addActionListener(e -> {
            JFileChooser chooser = new JFileChooser();
            chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
            if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
                localPathField.setText(chooser.getSelectedFile().getAbsolutePath());
            }
        });
        
        // 导入按钮
        importButton.addActionListener(e -> {
            String gitlabUrl = gitlabUrlField.getText().trim();
            String username = usernameField.getText().trim();
            String password = new String(passwordField.getPassword());
            String localPath = localPathField.getText().trim();
            boolean download = downloadCheckBox.isSelected();
            
            if (validateInput(gitlabUrl, username, password, localPath, download)) {
                importProjects(gitlabUrl, username, password, localPath, download);
            }
        });
        
        // 取消按钮
        cancelButton.addActionListener(e -> dispose());
        
        // 下载选项变化
        downloadCheckBox.addActionListener(e -> {
            localPathField.setEnabled(downloadCheckBox.isSelected());
            browseButton.setEnabled(downloadCheckBox.isSelected());
        });
    }
    
    private boolean validateInput(String gitlabUrl, String username, 
                                String password, String localPath, boolean download) {
        if (gitlabUrl.isEmpty()) {
            showError("请输入GitLab地址");
            return false;
        }
        if (username.isEmpty()) {
            showError("请输入用户名");
            return false;
        }
        if (password.isEmpty()) {
            showError("请输入密码");
            return false;
        }
        if (download && localPath.isEmpty()) {
            showError("请选择本地保存路径");
            return false;
        }
        return true;
    }
    
    private void importProjects(String gitlabUrl, String username, 
                              String password, String localPath, boolean download) {
        // 禁用按钮
        importButton.setEnabled(false);
        cancelButton.setEnabled(false);
        
        // 创建进度对话框
        JDialog progressDialog = new JDialog(this, "导入进度", false);
        JProgressBar progressBar = new JProgressBar();
        progressBar.setIndeterminate(true);
        progressDialog.add(progressBar);
        progressDialog.pack();
        progressDialog.setLocationRelativeTo(this);
        progressDialog.setVisible(true);
        
        // 在后台线程中执行导入
        SwingWorker<Void, String> worker = new SwingWorker<>() {
            @Override
            protected Void doInBackground() {
                try {
                    // 获取GitLab项目列表
                    List<GitLabProject> projects = GitLabService.getInstance()
                        .getProjects(gitlabUrl, username, password);
                    
                    // 更新表格
                    for (GitLabProject project : projects) {
                        publish(project.name());
                        tableModel.addRow(new Object[]{
                            true,
                            project.name(),
                            project.path(),
                            project.visibility()
                        });
                    }
                    
                    // 如果需要下载
                    if (download) {
                        for (int i = 0; i < tableModel.getRowCount(); i++) {
                            if ((Boolean) tableModel.getValueAt(i, 0)) {
                                GitLabProject project = projects.get(i);
                                String projectPath = localPath + File.separator + project.name();
                                GitLabService.getInstance().cloneProject(
                                    gitlabUrl, username, password,
                                    project.path(), projectPath
                                );
                            }
                        }
                    }
                    
                } catch (Exception e) {
                    publish("错误: " + e.getMessage());
                }
                return null;
            }
            
            @Override
            protected void process(List<String> chunks) {
                // 更新进度信息
                if (!chunks.isEmpty()) {
                    progressBar.setString(chunks.get(chunks.size() - 1));
                }
            }
            
            @Override
            protected void done() {
                progressDialog.dispose();
                importButton.setEnabled(true);
                cancelButton.setEnabled(true);
                
                try {
                    get();
                } catch (Exception e) {
                    showError("导入失败: " + e.getMessage());
                }
            }
        };
        
        worker.execute();
    }
    
    private void showError(String message) {
        JOptionPane.showMessageDialog(this, message, "错误", 
            JOptionPane.ERROR_MESSAGE);
    }
}